package com.cy.image;

/**
 * @author cy
 * @program: question-project
 * @description:
 * @date 2022-02-11 16:18:08
 */

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * 图片上传控制器
 */
@RestController
@RequestMapping("/api/upload")
public class ImageUploadController {
    //图片上传的路径
    @Value("${web.uploadPath}")
    private String webUploadPath;

    @RequestMapping("/uploadImage")
    public String uploadImage(@RequestParam("file") MultipartFile file){
        String Url = null;
        //获取名字
        String fileName = file.getOriginalFilename();
        //扩展名
        assert fileName != null;
        String fileExtensionName = fileName.substring(fileName.indexOf("."));
        //生成新的名称
        String newName = UUID.randomUUID().toString() + fileExtensionName;
        String path = webUploadPath;
        File fileDir = new File(path);
        if(!fileDir.exists()){
            //设置权限
            boolean b = fileDir.setWritable(true);
            boolean mkdirs = fileDir.mkdirs();
        }
        File targetFile = new File(path,newName);
        try{
            file.transferTo(targetFile);
            Url = "/" + targetFile.getName();
        }catch (Exception e){
            return  null;
        }
        return "/images" + Url;
    }
}
